package org.microblog.socket;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@ServerEndpoint("/ws")
public class ChatWebSocket {

    // 存储所有连接的客户端会话
    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

    // 当客户端连接时调用
    @OnOpen
    public void onOpen(Session session) {
        sessions.add(session);
        System.out.println("Client connected: " + session.getId());
        broadcast("User joined the chat.");
    }

    // 当客户端发送消息时调用
    @OnMessage
    public void onMessage(String message, Session sender) {
        System.out.println("Received: " + message);
        broadcast(message);
    }

    // 当客户端断开连接时调用
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
        System.out.println("Client disconnected: " + session.getId());
        broadcast("User left the chat.");
    }

    // 当发生异常时调用
    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    // 广播消息给所有连接的客户端
    private void broadcast(String message) {
        for (Session session : sessions) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}